<template>
  <div class="mid-box">
    <el-collapse-transition>
      <div v-show="btnGroup.search" class="main-box search-box">
        <el-form
          class="troila-form"
          ref="searchInfo"
          :model="searchObj"
          :inline="true"
          label-width="110px"
        >
          <el-form-item
            label="用户名"
            prop="loginName"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="全部"
              v-model="searchObj.loginName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="所属机构"
            prop="organizationId"
            class="troila-select-inline"
          >
            <treebox
              v-setwidth
              id="treebox"
              :list="treeArr"
              v-model="searchObj.organizationId"
              placeholder="全部"
              input
              :disabled="disabled"
              :clear="!disabled"
              onlyone
              :option="{ key: 'id', label: 'organizationName' }"
            ></treebox>
          </el-form-item>
          <el-form-item
            label="姓名"
            prop="userName"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="全部"
              v-model="searchObj.userName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号码"
            prop="phone"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="全部"
              v-model="searchObj.phone"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户状态"
            prop="status"
            class="troila-select-inline"
          >
            <el-select
              v-setwidth
              placeholder="全部"
              v-model="searchObj.status"
              clearable
              popper-class="troila-popper"
            >
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.dictName"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="添加日期" class="troila-select-inline">
            <el-date-picker
              v-model="createTime"
              v-setwidth
              placeholder="全部"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              type="daterange"
              popper-class="troila-popper"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="最后登录日期" class="troila-select-inline">
            <el-date-picker
              v-model="loginTime"
              v-setwidth
              placeholder="全部"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              type="daterange"
              popper-class="troila-popper"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>
    <!-- <div class="troila-group">
      <select-group
        v-model="btnGroup"
        :row="allTitle"
        :row-choose="chooseTitle"
        @rowChange="
          (arr) => {
            chooseTitle = arr
          }
        "
        @refresh="getList"
      />
    </div> -->
    <div class="main-box table-box">
      <div class="table-box-title ClearFloat">
        <!-- <i class="title-font">查询结果</i> -->
        <div class="troila-form">
          <el-button @click="submitSearch"
            ><unit-icon class="troila-icon" type="search" />查询</el-button
          >
          <el-button @click="resetForm"
            ><unit-icon class="troila-icon" type="refresh" />重置</el-button
          >
          <transtion-width>
            <span v-show="selection && selection.length > 0">
              <el-button
                v-limit="`system:roleManage:user`"
                @click="btnClick('batchDel')"
                ><unit-icon class="troila-icon" type="close" />移除</el-button
              >
            </span>
          </transtion-width>
        </div>
      </div>
      <unit-table
        v-if="!btnGroup.card"
        selection
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      />
      <!-- <unit-cards
        v-if="btnGroup.card"
        selection
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :opera="4"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      /> -->
      <pagination
        v-show="pager.total > pager.size"
        :pager="pager"
        @query="getList"
        ref="Pagerpagination"
      ></pagination>
    </div>
  </div>
</template>
<script>
export default {
  name: 'roleUserList',
  components: {},
  data() {
    return {
      searchObj: {
        loginName: '',
        organizationId: '',
        userName: '',
        phone: '',
        status: '',
        dateBegin: '',
        dateEnd: '',
        logdateBegin: '',
        logdateEnd: '',
      }, //搜索参数
      searchRes: {}, //搜索储存值
      loading: false,
      time: null, //时间组件值
      btnGroup: {
        //按钮组
        search: true,
        refresh: false,
        card: false,
      },
      pager: {
        // 页码
        total: 0,
        page: 1, //当前第几页
        size: 10, //每页显示的条数
      },
      dictionary: {
        // 字典信息
        // sex: [
        //   { dictName: '男', dictCode: '1' },
        //   { dictName: '女', dictCode: '0' },
        // ],
        // status: [
        // { dictName: '启用', dictCode: '1' },
        // { dictName: '禁用', dictCode: '0' },
        // ],
      },
      allTitle: [
        // 全部可显示表头
        {
          label: '用户名', //*表头名称
          code: 'loginName', //*对应数据项
          tooltip: true, //超出显示浮层
          width: 110, //最小宽
        },
        {
          label: '所属机构',
          code: 'organization',
          tooltip: true,
          width: 140,
          format: (item, key) => {
            return this.judgeEmpty(item[key] ? item[key].organizationName : '')
          },
        },
        {
          label: '姓名',
          code: 'userName',
          tooltip: true,
          width: 110,
        },
        {
          label: '手机号码',
          code: 'phone',
          width: 110,
          tooltip: true,
        },
        {
          label: '邮箱账号',
          code: 'email',
          tooltip: true,
          width: 110,
        },
        {
          label: '性别',
          code: 'sex',
          dict: 'sex', //需要查询字典对应的key
          width: 60,
        },
        {
          label: '添加时间',
          code: 'createTime',
          tooltip: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '创建人',
          code: 'createBy',
          tooltip: true,
          width: 110,
        },
        {
          label: '最后登录时间',
          code: 'loginTime',
          tooltip: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '用户状态',
          code: 'status',
          dict: 'status',
          style: {
            //该项style
            color: [
              { value: '#f54141', result: 0 },
              { value: '#00c533', result: 1 },
            ],
          },
        },
      ],
      chooseTitle: [
        //被选中显示表头
        'loginName',
        'organization',
        'userName',
        'phone',
        'email',
        'createTime',
        'loginTime',
        'status',
      ],
      tableData: [],
      tableOperation: [
        //表格操作
        // *code 对应图标, label 对应浮层显示文字, show 判断是否显示, color 图标颜色
        {
          code: 'delete',
          label: '移除',
          limit: 'system:roleManage:user',
        },
      ],
      selection: [], //表格选中行
      // showForm: false, //弹窗显示-新建修改
      showRole: false, //弹窗显示-分配角色
      editId: '',
      userId: '',
      disabled: false,
      treeArr: [],
      createTime: null,
      loginTime: null,
      row: null,
    }
  },
  computed: {
    tableTitle() {
      //表格表头
      return this.allTitle.filter(
        (item) => this.chooseTitle.indexOf(item.code) > -1
      )
    },
    userList() {
      let list = this.$store.state.dictionary.user_status
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'user_status')
      }
      this.dictionary.status = list
      let list1 = this.$store.state.dictionary.user_sex
      if (!list1) {
        this.$store.dispatch('dictionary/getDict', 'user_sex')
      }
      this.dictionary.sex = list1
      return list ? list : []
    },
  },
  methods: {
    // 获取列表
    getList() {
      let param = {
        pageNum: this.pager.page, //当前页
        pageSize: this.pager.size, //每页多少条
        roleIdStr: this.row.id,
        ...this.searchRes,
      }
      this.loading = true
      this.API.userManage
        .pageList(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.loading = false
            this.pager.total = res.data.total ? res.data.total : 0
            this.tableData = res.data.records
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          // console.log(e)
          this.loading = false
        })
    },

    // 重置
    resetForm() {
      // this.searchObj = {}
      this.$refs.searchInfo.resetFields()
      this.searchObj.dateBegin = ''
      this.searchObj.dateEnd = ''
      this.searchObj.logdateBegin = ''
      this.searchObj.logdateEnd = ''
      this.createTime = []
      this.loginTime = []
      this.searchRes = {}
      this.pager.page = 1
      this.getList()
    },
    // 搜索
    submitSearch() {
      this.searchRes = {
        ...this.searchObj,
        dateBegin:
          this.createTime && this.createTime.length > 0
            ? this.createTime[0]
            : '',
        dateEnd:
          this.createTime && this.createTime.length > 0
            ? this.createTime[1]
            : '',
        logdateBegin:
          this.loginTime && this.loginTime.length > 0 ? this.loginTime[0] : '',
        logdateEnd:
          this.loginTime && this.loginTime.length > 0 ? this.loginTime[1] : '',
      }
      this.pager.page = 1
      this.getList()
    },
    // 按钮操作
    btnClick(method) {
      // console.log(method)
      let text = ''
      switch (method) {
        case 'batchDel':
          text = '移除'
          break
        default:
          return
      }
      let name = this.selection.map((v) => `${v.userName}(${v.loginName})`)
      this.selection.length > 0
        ? this.$confirmFn(
            `您确定${text}以下用户吗？<div>${name.join('、')}</div>`,
            '提示',
            {
              callback: (action, instance) => {
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  // console.log(this.selection)
                  let postData = {
                    roleId: this.row.id,
                    userIds: this.selection.map((v) => v.id).join(','),
                  }
                  // console.log(postData)
                  this.API.roleManage.removeUser(postData).then((res) => {
                    if (res.code == 1) {
                      this.$alertFn.success(`${text}成功`)
                      this.getList()
                    } else {
                      this.$alertFn.error(`${text}失败`)
                      this.getList()
                    }
                  })
                }
              },
            }
          )
        : this.$alertFn.error(`请选择需要${text}的数据 ！`)
    },
    // 表格操作
    tableReturn(method, { row, prop, order, selection }) {
      // console.log(method, row, prop, order, selection)
      switch (method) {
        case 'selection':
          this.selection = [...selection]
          return
        case 'delete':
          this.$confirmFn(
            `您移除用户<span class='light'>${row.userName}(${row.loginName})</span>吗？`,
            '提示',
            {
              callback: (action, instance) => {
                // console.log(method, row)
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  this.API.roleManage
                    .removeUser({
                      roleId: this.row.id,
                      userIds: row.id,
                    })
                    .then((res) => {
                      if (res.code == 1) {
                        this.$alertFn.success(`移除成功`)
                        this.getList()
                      } else {
                        this.$alertFn.error(`移除失败`)
                        this.getList()
                      }
                    })
                }
              },
            }
          )
          return
        default:
          return
      }
    },
    back() {
      this.$router.go(-1)
    },
    getBase() {
      this.API.organization
        .pageList({ pageNum: 1, pageSize: 999999 })
        .then((res) => {
          if (res.data) {
            this.treeArr = res.data.records || []
          }
          // console.log(this.tableData)
        })
        .catch((err) => {})
    },
  },
  created() {
    if (this.$route.params.row) {
      this.row = this.$route.params.row
      this.submitSearch()
      this.getBase()
    } else {
      this.back()
    }
  },
  mounted() {},
  destroyed() {},
}
</script>
<style scoped>
</style>
